package View;

import DB.Evento.ControllerEvento;
import DB.Evento.EventoTable;
import DB.Util;
import Model.Evento;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;

public class EventosListView extends javax.swing.JFrame {
    
    public EventosListView() {
        initComponents();
        
        EventosTableModel etm = new EventosTableModel();
        
        jTable1.setModel(etm);
        jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(30);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(70);
        jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        btAdd = new javax.swing.JButton();
        btDelete = new javax.swing.JButton();

        setTitle("LISTA DE EVENTOS");

        jTable1.setModel(new EventosTableModel());
        jTable1.setInheritsPopupMenu(true);
        jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                changeOnClick(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        btAdd.setText("Cadastrar");
        btAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAddActionPerformed(evt);
            }
        });

        btDelete.setText("Excluir");
        btDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btDeleteActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 640, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btDelete)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btAdd)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btAdd)
                    .addComponent(btDelete))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        setSize(new java.awt.Dimension(676, 373));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    //Duplo Clique - Double click
    private void changeOnClick(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_changeOnClick
        if (evt.getClickCount() < 2) {
            return;
        }
        int row = jTable1.getSelectedRow();
        
        ControllerEvento uc = ControllerEvento.getInstance();
        ArrayList<Evento> evento = uc.getAll();
        
        EventoDetailView edv = new EventoDetailView(evento.get(row));
        edv.setVisible(true);
    }//GEN-LAST:event_changeOnClick

    private void btDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btDeleteActionPerformed
        int row = jTable1.getSelectedRow();
        
        if (row >= 0) {
            
            ControllerEvento ce = ControllerEvento.getInstance();
            ArrayList<Evento> eventos = ce.getAll();
            
            Evento e = eventos.get(row);
            System.out.println(e.toString());
            ce.delete(e.getId());
            
            this.setVisible(false);
            
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    EventosListView listView = new EventosListView();
                    listView.setVisible(true);
                }
            });
        } else {
            JOptionPane.showMessageDialog(null, "Nenhum evento selecionado para exclusão..", "Erro", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btDeleteActionPerformed

    private void btAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAddActionPerformed
        EventoAddNew an = new EventoAddNew();
        an.setVisible(true);
    }//GEN-LAST:event_btAddActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(EventosListView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EventosListView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EventosListView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EventosListView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new EventosListView().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAdd;
    private javax.swing.JButton btDelete;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables

    class EventosTableModel extends AbstractTableModel {
        
        ArrayList<Evento> tableData;
        String[] columnNames;
        
        public EventosTableModel() {
            ControllerEvento ce = ControllerEvento.getInstance();
            this.tableData = ce.getAll();
            this.columnNames = EventoTable.allColumns;
        }
        
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Evento evento = tableData.get(rowIndex);
            
            switch (columnIndex) {
                case 0:
                    return evento.getId();
                case 1:
                    return evento.getNome();
                case 2:
                    return evento.getValor();
                case 3:
                    return evento.getVagas();
                case 4:
                    return Util.getFormatoData().format(evento.getDataEvento());
                case 5:
                    return Util.getFormatoData().format(evento.getInicioInscricoes());
                case 6:
                    return Util.getFormatoData().format(evento.getFimInscricoes());

                // Comentado para que esses campos não aparecam na tela da tabela
//            case 5:
//                return user.getCpf();
//            case 6:
//                return user.getEmail();
//            case 7:
//                return user.getDataNascimento();
//            case 8:
//                return user.getNomeCracha();
//            case 9:
//                return user.getSexo();
//            case 10:
//                return user.getEndereco();
//            case 11:
//                return user.getCidade();
//            case 12:
//                return user.getEstado();
//            case 13:
//                return user.getPais();
//            case 14:
//                return user.getCep();
//            case 15:
//                return user.getTelefone();
//            case 16:
//                return user.getCelular();
                default:
                    return "";
            }
        }
        
        @Override
        public int getRowCount() {
            return tableData.size();
        }
        
        @Override
        public int getColumnCount() {
            return EventoTable.allColumns.length;
        }
        
        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }
    }
}
